package pl.egraveyard.dao;

import java.lang.reflect.ParameterizedType;

import org.apache.commons.lang.Validate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
/**
  * Klasa abstracyjna po ktorej maja dziedziczyc wszsytkie DAO. Zawiera w sobie
 * sessionFactory oraz implementacje podstawowych operacji CRUD
 * @param <T> klasa na ktorej beda wykonywane operacje
 * 
 * @author gunos
 */
public abstract class AbstractDaoSupportImpl<T>  implements AbstractDaoSupport<T>{
	private SessionFactory sessionFactory;
	private Class<T> entityClass;

	/**
	 * Domyslny konstruktor
	 */
	@SuppressWarnings("unchecked")
	public AbstractDaoSupportImpl() {
		this.entityClass = (Class<T>) ((ParameterizedType) this.getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];

	}
	
	/**
	 * @param sessionFactory
	 *            the sessionFactory to set
	 */
	public void setSessionFactory(final SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	/**
	 * @return aktualna sesje 
	 */
	public Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	@SuppressWarnings("unchecked")
	public T read(Integer id){
		Validate.notNull(id);
		T obj =  (T) getCurrentSession().createCriteria(entityClass)
				.add(Restrictions.eq("id", id)).uniqueResult();
		getCurrentSession().evict(obj);
		return obj;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void create(Object obj) {
		Validate.notNull(obj);
		getCurrentSession().persist(obj);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void update(Object obj) {
		Validate.notNull(obj);
		getCurrentSession().update(obj);	
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void delete(Object obj) {
		Validate.notNull(obj);
		getCurrentSession().delete(obj);
		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void delete(Integer id) {
		Validate.notNull(id);
			T tmp = this.read(id);
		if (tmp != null) {
			getCurrentSession().delete(tmp);
		}
	}
}
